import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.MulticastSocket;
import java.util.Timer;
import java.util.TimerTask;
//Xaveco : Gateway 143.106.16.148 IP: 143.106.16.163  Bcast:143.106.16.191  Masc:255.255.255.192
//Dickens: Gateway 143.106.16.254 IP: 143.106.16.210  Bcast:143.106.16.255  Masc:255.255.255.192
//Pateta : Gateway 143.106.16. 64 IP: 143.106.16.63   Bcast:143.106.16. 63  Masc:255.255.255.192
public class Broadcaster {
	static int port=56792;
	
	public static void main(String[] args) throws IOException {
		//final InetAddress addr = InetAddress.getByName("143.106.16.255"); //Testa broadcast 
		final InetAddress addr = InetAddress.getByName("225.4.5.6"); //Testa Multicast
		
		final DatagramSocket socket;
		if (addr.isMulticastAddress()) {
			socket = new MulticastSocket(port);
			((MulticastSocket)socket).joinGroup(addr);
			System.out.println("Multicast to " + addr.getHostAddress());
		} else {
			socket = new DatagramSocket(port);
			socket.setBroadcast(true);
			System.out.println("Broadcast to " + addr.getHostAddress());
		}
		
		//TImer que envia pacotes pelo socket
		Timer t = new Timer("Send");
		t.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				try {
					byte[] buf = "Oi mundo".getBytes();
					DatagramPacket pack = new DatagramPacket(buf, buf.length, new InetSocketAddress(addr, port));
					socket.send(pack);
					System.out.println("Sent to " + pack.getSocketAddress());
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}, 0, 1000); //A cada 1s
		
		
		//Looping para receber pacotes pelo socket
		byte[] buf = new byte[1024];
		DatagramPacket pack = new DatagramPacket(buf, buf.length);
		while (true) {
			socket.receive(pack);
			String s = new String(buf, 0, pack.getLength());
			System.err.println("Received: '" + s + "' from " + pack.getAddress());
		}
	}
}
